package com.stylefeng.guns.modular.borrowing.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.borrowing.service.IBorrowingInfoService;
import com.stylefeng.guns.modular.borrowing.service.ICustomerinfoService;
import com.stylefeng.guns.modular.cash.service.IDetailsService;
import com.stylefeng.guns.modular.rate.service.IRateService;
import com.stylefeng.guns.modular.system.model.BorrowingInfo;
import com.stylefeng.guns.modular.system.model.Customerinfo;
import com.stylefeng.guns.modular.system.model.Details;
import com.stylefeng.guns.modular.system.model.Rate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 应收应付报表控制器
 *
 * @author fengshuonan
 * @Date 2018-07-04 11:24:01
 */
@Controller
@RequestMapping("/borrowingInfo")
public class BorrowingInfoController extends BaseController {

    private String PREFIX = "/borrowing/borrowingInfo/";

    @Autowired
    private IBorrowingInfoService borrowingInfoService;

    @Autowired
    private IDetailsService detailsService;
    @Autowired
    private IRateService rateService;

    @Autowired
    private ICustomerinfoService customerinfoService;

    /**
     * 跳转到应收应付报表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "borrowingInfo.html";
    }

    /**
     * 跳转到添加应收应付报表
     */
    @RequestMapping("/borrowingInfo_add")
    public String borrowingInfoAdd(Model model) {
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        EntityWrapper<Details> wrapper = new EntityWrapper<>();
        wrapper.eq("type",1);
        List<Details>  detailsList=detailsService.selectList(wrapper);
        Details details = new Details();
        details.setType(1);
        details.setName("请选择");
        detailsList.add(0,details);
        model.addAttribute("Customerinfos",customerList);
        model.addAttribute("Details",detailsList);
        return PREFIX + "borrowingInfo_add.html";
    }


    /**
     * 删除资金预算
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer borrowingInfoId) {
        borrowingInfoService.deleteById(borrowingInfoId);
        return SUCCESS_TIP;
    }


    /**
     * 跳转到期初余额
     */
    @RequestMapping("/borrowingInfo_addBalance")
    public String borrowingInfo_addBalance(Model model) {
        return PREFIX + "borrowingInfo_addBalance.html";
    }

    /**
     * 跳转到修改应收应付报表
     */
    @RequestMapping("/borrowingInfo_update/{borrowingInfoId}")
    public String borrowingInfoUpdate(@PathVariable Integer borrowingInfoId, Model model) {
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        BorrowingInfo borrowingInfo = borrowingInfoService.selectById(borrowingInfoId);
        model.addAttribute("item",borrowingInfo);
        model.addAttribute("Customerinfos",customerList);
        LogObjectHolder.me().set(borrowingInfo);
        return PREFIX + "borrowingInfo_edit.html";
    }

    /**
     * 获取应收应付报表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@Platform String platform,@RequestParam(required = false) Integer type,@RequestParam(required = false) String beginDate,@RequestParam(required = false) String  endDate
                            ,String contact) throws Exception {
        Page<BorrowingInfo> page = new PageFactory<BorrowingInfo>().defaultPage();
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.eq("platform",platform);
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("rev_date", beginDate);
        }else{
            wrapper.ge("rev_date", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("rev_date", endDate);
        }else{
            wrapper.le("rev_date", DateUtil.today(1));
        }
        if(type!=null){
            wrapper.eq("type", type);
        }
        if (StringUtils.isNotBlank(contact))
            wrapper.eq("contact",contact);
        wrapper.orderBy("rev_date",true);
        Page<BorrowingInfo> object = borrowingInfoService.selectPage(page,wrapper);
        page.setRecords((List<BorrowingInfo>)new BaseModelWarpper(object.getRecords(),BorrowingInfo.class).warpToObj());
        latelyReord(object,platform,beginDate);
        return super.packForBT(page);
    }



    /**
     * 描述:最近一条
     * 创建人: xiang
     * 日期: 2018/8/16
    * 时间: 15:46
    */
    public void latelyReord(Page<BorrowingInfo> object, String platform, String beginDate){
        //没有记录 默认查出最近一条
            BorrowingInfo borrowingInfo1= borrowingInfoService.selectOne( new  EntityWrapper<BorrowingInfo>()
                    .eq("platform",platform)
                    .lt("rev_date", beginDate)
                    .orderBy("rev_date DESC")
                    .orderBy("id desc")
                    .last("LIMIT 1")
            );
            if(borrowingInfo1!=null){
                BorrowingInfo borrowingInfo = new BorrowingInfo();
                borrowingInfo.setNote("上笔余额");
                borrowingInfo.setBalance(borrowingInfo1.getBalance());
                List<BorrowingInfo> list = object.getRecords();
                list.add(0,borrowingInfo);
                object.setRecords(list);
            }
    }



    /**
     * 应收应付报表详情
     */
    @RequestMapping(value = "/detail/{borrowingInfoId}")
    @ResponseBody
    public Object detail(@PathVariable("borrowingInfoId") Integer borrowingInfoId) {
        return borrowingInfoService.selectById(borrowingInfoId);
    }

    /**
     * 描述:导出应收应付
     * 创建人: laoyu
     * 日期: 2018/8/6 0006
     * 时间: 下午 5:04
     */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response, @RequestParam(required = true)String beginDate
                                                                    ,@RequestParam(required = true)String endDate) throws Exception  {


        //查询要导出工资
        if (org.apache.commons.lang.StringUtils.isBlank(beginDate)){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请选择要导出开始时间");
        }
        if (org.apache.commons.lang.StringUtils.isBlank(endDate)){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请选择要导出结束时间");
        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String platform = ShiroKit.getUser().getDeptcode();//获取当前平台
        //组装插叙数据
        EntityWrapper<BorrowingInfo> wrapper  = new EntityWrapper<>();
        wrapper.eq("platform",platform);
//        wrapper.like("rev_date",revDate);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);

        //初始化导出的模板表格
        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/borrowingInfo.xlsx");
        Map<String, Object> map = borrowingInfoService.load(borrowingInfoService.selectList(wrapper),platform,beginDate,endDate);

        modelMap.put(TemplateExcelConstants.FILE_NAME, platform+beginDate+"--"+endDate+"收支及成本费用分类明细表（PS）");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }


    /**
     * 修改应收应付报表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(BorrowingInfo borrowingInfo) {
        BorrowingInfo oldBorrowingInfo = borrowingInfoService.selectById(borrowingInfo.getId());
        borrowingInfo.setUpdatetime(new Date());
        borrowingInfoService.update(borrowingInfo,oldBorrowingInfo);

        return SUCCESS_TIP;
    }


    /**
     * 新增应收应付报表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(BorrowingInfo borrowingInfo) {
        double piseotormb = 0;

        if (StringUtils.isBlank(borrowingInfo.getRevDate().toString()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表统计时间不能为空");

        if (borrowingInfo.getPisoAmount()!=null){
            //获取汇率
            Rate rate = rateService.search(new SimpleDateFormat("yyyy-MM").format(borrowingInfo.getRevDate()));
            piseotormb =borrowingInfo.getPisoAmount()/rate.getRate();
        }

        borrowingInfo.setCreattime(new Date());
        borrowingInfo.setOrderNumber(String.valueOf(System.currentTimeMillis()));
        borrowingInfo.setPisoToRmb(piseotormb);
        borrowingInfoService.sav(borrowingInfo);

        return SUCCESS_TIP;
    }



    /**
     * 新增期数余额
     */
    @RequestMapping(value = "/addBalance")
    @ResponseBody
    public Object addBalance(BorrowingInfo borrowingInfo) {
        double piseotormb = 0;
        if (borrowingInfo.getRevDate()==null)
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表统计时间不能为空");
        if (borrowingInfo.getBalance()==null)
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"余额不能为空");
        borrowingInfo.setOrderNumber(genItemId().toString());
        borrowingInfo.setType(BorrowingInfo.Enum_Type.应付.value);
        borrowingInfo.setNote("期初余额");
        borrowingInfoService.insert(borrowingInfo);
        return SUCCESS_TIP;
    }



    /**
     * 描述:应付应收合计
     * 创建人: xiang
     * 日期: 2018/8/9
     * 时间: 10:13
     */
    @RequestMapping(value = "/tatol")
    @ResponseBody
    public Object total(@Platform String platform,@RequestParam(required = false) Integer type, @RequestParam(required = false) String beginDate, @RequestParam(required = false) String  endDate) throws Exception {
        //初始化日期
        if(!StringUtils.isNotBlank(beginDate)) {
            beginDate=DateUtil.today(0);
        }
        if(!StringUtils.isNotBlank(endDate)) {
            endDate= DateUtil.today(1);
        }
        Object object=borrowingInfoService.tatol(type,beginDate,endDate,platform);
        return object;
    }

  


}
